package com.lhw.ai.controller;

import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import com.alibaba.cloud.ai.memory.jdbc.MysqlChatMemoryRepository;
import com.lhw.ai.constant.AppConstants;
import com.lhw.ai.service.BailianService;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.ChatMemoryRepository;
import org.springframework.ai.chat.memory.MessageWindowChatMemory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import reactor.core.publisher.Flux;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 测试controller
 *
 * @author: lwh
 * @since: 2025/07/24 15:23:38
 * @version: 1.0
 */
@Tag(name = "聊天接口", description = "提供AI聊天相关接口")
@RestController
@RequestMapping("/helloworld")
public class HelloController {
    private final ChatClient dashScopeChatClient;
    @Resource
    private BailianService bailianService;
    @Resource
    private JdbcTemplate jdbcTemplate;



    public HelloController(ChatClient.Builder chatClientBuilder) {
        this.dashScopeChatClient = chatClientBuilder
                .defaultSystem(AppConstants.DEFAULT_PROMPT)
                // 实现 Logger 的 Advisor
                .defaultAdvisors(
                        new SimpleLoggerAdvisor()
                                )
                // 设置 ChatClient 中 ChatModel 的 Options 参数
                .defaultOptions(
                        DashScopeChatOptions.builder()
                                            .withTopP(0.7)
                                            .build()
                               )
                .build();
    }

    /**
     * ChatClient 简单调用
     */
    @Operation(summary = "简单聊天", description = "使用DashScope ChatClient进行简单的聊天对话")
    @ApiResponse(responseCode = "200", description = "成功返回聊天结果", 
        content = @Content(mediaType = "application/json", 
        schema = @Schema(implementation = String.class)))
    @GetMapping("/simple/chat")
    public String simpleChat(
            @Parameter(description = "用户查询内容", example = "你好，很高兴认识你，能简单介绍一下自己吗？") 
            @RequestParam(value = "query", defaultValue = "你好，很高兴认识你，能简单介绍一下自己吗？") String query) {

        return dashScopeChatClient.prompt(query).call().content();
    }


    /**
     * ChatClient 流式调用
     */
    @Operation(summary = "流式聊天", description = "使用DashScope ChatClient进行流式聊天对话，支持对话历史记录")
    @ApiResponse(responseCode = "200", description = "成功返回流式聊天结果", 
        content = @Content(mediaType = "application/json", 
        schema = @Schema(implementation = String.class)))
    @GetMapping("/stream/chat")
    public Flux<String> streamChat(
            @Parameter(description = "用户查询内容", example = "你好，很高兴认识你，能简单介绍一下自己吗？") 
            @RequestParam(value = "query", defaultValue = "你好，很高兴认识你，能简单介绍一下自己吗？") String query,
            HttpServletResponse response,
            @Parameter(description = "对话ID，用于标识对话历史") 
            @RequestParam(value = "conversationId", required = false) String conversationId) {

        response.setCharacterEncoding("UTF-8");

        // 构造 ChatMemoryRepository 和 ChatMemory
        ChatMemoryRepository chatMemoryRepository = MysqlChatMemoryRepository.mysqlBuilder()
                                                                             .jdbcTemplate(
                                                                                     jdbcTemplate)
                                                                             .build();
        ChatMemory chatMemory = MessageWindowChatMemory.builder()
                                                       .chatMemoryRepository(chatMemoryRepository)
                                                       .build();

        return dashScopeChatClient.prompt(query).advisors(
                MessageChatMemoryAdvisor.builder(chatMemory).conversationId(conversationId).build()
                // 增加mysql memary
                                                         ).stream().content();
    }


}